local sock, err = ngx.req.socket()
if not sock then
    ngx.log(ngx.ERR, 'stream system failed to get request socket:', err)
    return ngx.exit(ngx.ERROR)
end

local req, err = sock:receive()
if not req then
    ngx.log(ngx.ERR, 'stream system failed to receive:', err)
    return ngx.exit(ngx.ERROR)
end

local dns = server:new()
local request, err = dns:decode_request(req)
if not request then
    ngx.log(ngx.ERR, "stream system failed to decode request: ", err)

    local resp = dns:encode_response()
    local ok, err = sock:send(resp)
    if not ok then
        ngx.log(ngx.ERR, "stream system failed to send response: ", err)
        return ngx.exit(ngx.ERROR)
    end

    return
end

ngx.log(ngx.DEBUG, 'request.questions len:', #request.questions)
local query = request.questions[1]
ngx.log(ngx.DEBUG, "qname: ", query.qname, " qtype: ", query.qtype)

local subnet = request.subnet[1]
if subnet then
    ngx.log(ngx.DEBUG, "subnet addr: ",  subnet.address, " mask: ", subnet.mask, " family: ", subnet.family)
end

local data = ngx.shared.hosts:get(query.qname)

if query.qtype == server.TYPE_CNAME or query.qtype == server.TYPE_AAAA or query.qtype == server.TYPE_A then
    if data then
        ngx.log(ngx.DEBUG, 'cname data:', data)
        local _table = stringExt:split(data, '|')
        if not _table or #_table < 2 then
        else
            local type = tonumber(_table[1])
            local err = nil
            if type == server.TYPE_A then
                err = dns:create_a_answer(query.qname, 1, _table[2])
            end
            if type == server.TYPE_AAAA then
                err = dns:create_aaaa_answer(query.qname, 1, _table[2])
            end
            if err then
                ngx.log(ngx.ERR, "stream system failed to create cname answer: ", err)
                return
            end
        end
    end
else
    ngx.log(ngx.INFO, 'stream system filter out question type:', query.qtype)
end
local resp = dns:encode_response()
local ok, err = sock:send(resp)
if not ok then
    ngx.log(ngx.ERR, "stream system failed to send response: ", err)
    return
end